package com.kangjia.jasckson;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.kangjia.jasckson.hander.DateJsonDeserializer;
import com.kangjia.jasckson.hander.DateJsonSerializer;
import com.kangjia.jasckson.hander.DecimalJsonSerializer;
import com.kangjia.jasckson.hander.LocalDateJsonDeserializer;
import com.kangjia.jasckson.hander.LocalDateJsonSerializer;
import com.kangjia.jasckson.hander.LocalDateTimeJsonDeserializer;
import com.kangjia.jasckson.hander.LocalDateTimeJsonSerializer;
import com.kangjia.jasckson.hander.LocalTimeJsonDeserializer;
import com.kangjia.jasckson.hander.LocalTimeJsonSerializer;


/**
 * 数据映射,jackjson数据转换
 * 
 * @author sunshulin
 * 
 */
public class DataMapper extends ObjectMapper {

	private static final long serialVersionUID = -2082870693873998290L;

	private static DataMapper datamapper;

	private DataMapper() {
		SimpleModule module = new SimpleModule();
		module.addSerializer(Date.class, new DateJsonSerializer());
		module.addDeserializer(Date.class, new DateJsonDeserializer());
		module.addSerializer(BigDecimal.class, new DecimalJsonSerializer());
		module.addSerializer(LocalDate.class, new LocalDateJsonSerializer());
		module.addDeserializer(LocalDate.class, new LocalDateJsonDeserializer());
		module.addSerializer(LocalDateTime.class, new LocalDateTimeJsonSerializer());
		module.addDeserializer(LocalDateTime.class, new LocalDateTimeJsonDeserializer());
		module.addSerializer(LocalTime.class, new LocalTimeJsonSerializer());
		module.addDeserializer(LocalTime.class, new LocalTimeJsonDeserializer());
		this.setSerializationInclusion(Include.NON_NULL);
		this.registerModule(module);
	}

	public static DataMapper getInstance() {
		if (datamapper == null) {
			synchronized (DataMapper.class) {
				datamapper = new DataMapper();
			}
		}
		return datamapper;
	}

	public static <T> String write(T t) {
		try {
			return getInstance().writeValueAsString(t);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}

	public static <T> T read(String json, Class<T> clazz) {
		try {
			return getInstance().readValue(json.getBytes(), clazz);
		} catch (JsonParseException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
